package pl.pkolodziej.platform.controller.login;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import pl.pkolodziej.platform.service.course.CourseService;
import pl.pkolodziej.platform.service.course.UserCourseService;
import pl.pkolodziej.platform.service.mail.MailService;
import pl.pkolodziej.platform.service.schedule.ScheduleService;
import pl.pkolodziej.platform.service.user.UserService;
import pl.pkolodziej.platform.vo.SystemInfo;
import pl.pkolodziej.platform.vo.course.Course;
import pl.pkolodziej.platform.vo.course.UserCourseInfo;
import pl.pkolodziej.platform.vo.schedule.Schedule;
import pl.pkolodziej.platform.vo.user.Authority;
import pl.pkolodziej.platform.vo.user.CreateUser;
import pl.pkolodziej.platform.vo.user.User;
import pl.pkolodziej.utils.FormValidation;

@Controller
public class LoginController {

	@Autowired
	public UserService userService;
	
	@Autowired
	public UserCourseService userCourseService;
	
	@Autowired
	public CourseService courseService;
	
	@Autowired
	public MailService mailService;
	
	@Autowired
	public ScheduleService scheduleService;
	
	@RequestMapping(value="/login")
	public String showLoginForm(HttpServletRequest request){
		SystemInfo.app_url = request.getRequestURL().substring(0,(request.getRequestURL().length() - request.getServletPath().length()));
		return "login/login";
	}
	
	@RequestMapping(value="/verify")
	public String sendVerification() {
		return "login/login?verifictaionSent=1";
	}
	
	@RequestMapping(value="/logout")
	public String showLogout(){
		return "login/logout";
	}
	
	@RequestMapping(value = "/forgot", method = RequestMethod.GET)
	public String showForgot(Map<String, Object> map) {
		map.put("user", new User());
		return "login/forgot";
	}

	@RequestMapping(value = "/forgot", method = RequestMethod.POST)
	public String sendPassword(@ModelAttribute("user") User user,
			BindingResult result) {
		User u = userService.getUserPassword(user.getUsername());
		try {
			mailService.sendPassword(u);
		} catch (Exception e) {
			return "redirect:/forgot?userNotFound=1";
		}
		return "redirect:/forgot?emailSent=1";
	}
	
	@RequestMapping(value = "/createAccount", method = RequestMethod.GET)
	public String createAccount(Map<String, Object> map, HttpServletRequest request) {
		map.put("createUser", new CreateUser());
		return "login/create";
	}

	@RequestMapping(value = "/createAccount", method = RequestMethod.POST)
	public String addUser(@ModelAttribute("createUser") CreateUser createUser,
			BindingResult result, HttpServletResponse response) {
		Authority authority = new Authority();
		authority.setAuthority("ROLE_USER");
		authority.setUsername(createUser.getUsername());
		if (!FormValidation.checkLogin(createUser.getUsername()))
			return "redirect:/createAccount?usernameFaild=1";
		if (!FormValidation.checkPassword(createUser.getNewPassword(), createUser.getRePassword()))
			return "redirect:/createAccount?passwordFaild=1";
		if (!FormValidation.checkCode(createUser.getCode()))
			return "redirect:/createAccount?codeFaild=1";
		User user = new User();
		user.setUsername(createUser.getUsername());
		user.setPassword(createUser.getNewPassword());
		user.setEnabled(true);
		
		try {
			userService.addUser(user, authority, FormValidation.group(createUser.getCode()));
		}catch (DataIntegrityViolationException e){
			return "redirect:/createAccount?userExist=1";
		}catch(Exception e) {
			return "redirect:/createAccount?sqlError=1";
		}
		try {
			for(int i : FormValidation.decryptUserCode(createUser.getCode())){
				UserCourseInfo uci = new UserCourseInfo();
				uci.setUsername(user.getUsername());
				for (Course c : courseService.listCourses()){
					if(c.getCourse_id()==i)
						uci.setCourse(c);
				}
				userCourseService.addUserCourse(uci);
				
				Schedule s = new Schedule();
				s.setUsername(user.getUsername());
				s.setGroup_id(FormValidation.group(createUser.getCode()));
				s.setCourseId(uci.getCourse().getCourse_id());
				s.setTitle(StringEscapeUtils.escapeHtml(uci.getCourse().getTitle()));
				s.setActive(false);
				scheduleService.addSchedule(s);
			}
		}catch(Exception e) {
			return "redirect:/createAccount?codeFaild=1";
		}
		try {
			mailService.sendVerificationMail(user, userService.createKey(user), "url");
		}catch(Exception e) {

		}
		return "redirect:/login?create=1";
	}
	
	

}
